import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import AsyncWebsocketConsumer, AsyncJsonWebsocketConsumer, WebsocketConsumer
from django.http import request


class ChatConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        print("xxxxxx")
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"chat_{self.room_name}"
        # 加入组
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        print(self.scope["headers"][-1][1])
        # 前端传参，将token作为协议传到后台，后台返回也将协议返回
        await self.accept(subprotocol=self.scope["subprotocols"][0])


    async def disconnect(self, code):
        await self.channel_layer.group_discard(
            self.room_group_name, self.channel_name
        )

    """ AsyncJsonWebsocketConsumer 实现 """
    async def receive_json(self, text_data=None):
        print(text_data)
        # 发送消息到 room group
        await self.channel_layer.group_send(
            self.room_group_name, {"type": "chat.message", "message": text_data['message']}
        )

    
    # 接收消息从 room group
    async def chat_message(self, event):
        print(event)
        # Send message to WebSocket
        await self.send_json({"message": event["message"]})
    
    """ AsyncWebsocketConsumer 实现 """
    # 接收消息从websocket
    # async def receive(self, text_data=None):
    #     text_data_json = json.loads(text_data)
    #     message = text_data_json["message"]
    #     # 发送消息到 room group
    #     await self.channel_layer.group_send(
    #         self.room_group_name, {"type": "chat.message", "message": message}
    #     )

    
    # # 接收消息从 room group
    # async def chat_message(self, event):
    #     message = event["message"]

    #     # Send message to WebSocket
    #     await self.send(text_data=json.dumps({"message": message}))


class Tuisong(WebsocketConsumer):
    def connect(self):
        self.room_group_name = self.scope['url_route']['kwargs']['room_name']
        print(self.room_group_name)
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
 
 
        self.accept()
 
 
 
    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
 
    # 主动推送
    def tui_song(self, event):
        ggg = event['msg']
        self.send(text_data=json.dumps({
            'message': ggg
        }))
